<template>
	<CustomNavBar title="发票列表" />
	<view class="container">
		<view class="fixed-header">
			<view class="tabs">
				<view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', { active: currentTab === index }]" @click="changeTab(index)">
					{{ tab.name }}
				</view>
			</view>
		</view>

		<scroll-view scroll-y class="order-list" @scrolltolower="handleScrollToLower">
			<!-- 月份分组 -->
			<view v-for="(group, month) in groupedOrders" :key="month" class="month-group">
				<view class="month-header">{{ month }}</view>
				<view class="order-items-container">
					<view v-for="(order, index) in group" :key="order.id" class="order-item">
						<view class="checkbox-container">
              <RoundCheckbox
                  :checked="selectedOrders.includes(order.id)"
                  color="#1DCFB7"
                  :size="40"
                  @change="(checked) => handleOrderCheck(order.id, checked)"
              />
            </view>
					<view class="order-type-badge">{{ order.badge }}</view>
            <view class="order-info" @click="openDetail(order)">
              <view class="info-line">
                <text class="location">{{ order.location }}</text>
                <text class="amount">¥{{ order.amount.toFixed(2) }}</text>
              </view>
              <view class="info-line">
                <text class="plate-number">{{ order.plateNumber }}</text>
              </view>
              <view class="info-line">
                <text class="date">{{ order.date }}</text>
              </view>
						</view>
					</view>
				</view>
			</view>
			<view class="loading-tip" v-if="loading">
				<text>加载中...</text>
			</view>
			<view class="loading-tip" v-else-if="!hasMore && filteredOrders.length > 0">
				<text>没有更多数据了</text>
			</view>
			<view class="loading-tip" v-else-if="filteredOrders.length === 0">
				<text>暂无可开发票订单</text>
			</view>
		</scroll-view>

		<view class="footer">
			<view class="footer-top">
				<view class="select-all">
          <view class="checkbox-wrapper">
            <RoundCheckbox
                :checked="isSelectAll"
                color="#1DCFB7"
                :size="40"
                @change="handleSelectAllChange"
            />
            <text class="select-all-text">全选</text>
          </view>
				</view>
				<view class="reminder-text">温馨提示：消费后365天内可开具电子发票</view>
			</view>
			<view class="divider"></view>
			<view class="action-buttons">
				<view class="action-btn" @click="navigateToHistory">开票历史</view>
				<view class="action-btn" @click="navigateToTitles">管理抬头</view>
			</view>
			<view class="divider"></view>
			<view class="footer-bottom">
				<view class="footer-left">
					<view class="summary">
						<text class="total-label">合计：</text>
						<text class="total-amount">¥{{ totalAmount.toFixed(2) }}</text>
					</view>
					<text class="order-count">已选订单：{{ selectedOrders.length }}笔</text>
				</view>
				<view class="btn-container">
					<view class="next-step-btn" :disabled="selectedOrders.length === 0" @click="nextStep">申请开票</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import CustomNavBar from '@/components/CustomNavBar.vue';
import RoundCheckbox from '@/components/RoundCheckbox.vue';
import InvoiceApi from '@/api/app/invoice.js';

const tabs = ref([
	{ name: '全部', type: 'all' },
	{ name: '充电', type: 'charging' },
	{ name: '停车', type: 'parking' },
]);
const currentTab = ref(1); // 默认选中充电tab

// 列表与分页状态
const orders = ref([]);
const selectedOrders = ref([]);
const currentPage = ref(1);
const pageSize = ref(1);
const hasMore = ref(true);
const loading = ref(false);

// 统一解析中文日期（兼容各端）
const parseCNDate = (str) => {
    // 支持格式：YYYY年M月D日 HH:mm:ss 或仅日期
    const m = str.match(/(\d{4})年(\d{1,2})月(\d{1,2})日(?:\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?/);
    if (!m) {
        return new Date(NaN);
    }
    const year = Number(m[1]);
    const month = Number(m[2]) - 1; // Date中的月份从0开始
    const day = Number(m[3]);
    const hour = Number(m[4] ?? 0);
    const minute = Number(m[5] ?? 0);
    const second = Number(m[6] ?? 0);
    return new Date(year, month, day, hour, minute, second);
};

const filteredOrders = computed(() => {
    const type = tabs.value[currentTab.value].type;
    const base = type === 'all' ? orders.value : orders.value.filter(order => order.type === type);
    // 使用副本排序，避免影响原始数组
    const filtered = base.slice().sort((a, b) => parseCNDate(b.date) - parseCNDate(a.date));
    return filtered;
});

const groupedOrders = computed(() => {
    const groups = {};
    filteredOrders.value.forEach(order => {
        const d = parseCNDate(order.date);
        const key = `${d.getFullYear()}年${d.getMonth() + 1}月`;
        if (!groups[key]) groups[key] = [];
        groups[key].push(order);
    });

    // 按月份排序（从近到远）
    const sortedMonths = Object.keys(groups).sort((a, b) => {
        const ya = Number(a.match(/(\d+)年/)[1]);
        const ma = Number(a.match(/(\d+)月/)[1]);
        const yb = Number(b.match(/(\d+)年/)[1]);
        const mb = Number(b.match(/(\d+)月/)[1]);
        if (ya !== yb) return yb - ya;
        return mb - ma;
    });

    const result = {};
    sortedMonths.forEach(m => { result[m] = groups[m]; });
    return result;
});

const totalAmount = computed(() => {
	return selectedOrders.value.reduce((sum, id) => {
		const order = orders.value.find(o => o.id === id);
		return sum + (order ? order.amount : 0);
	}, 0);
});

const isSelectAll = computed(() => {
	if (filteredOrders.value.length === 0) return false;
	return selectedOrders.value.length === filteredOrders.value.length;
});

const changeTab = (index) => {
	currentTab.value = index;
	// 切换tab时重置分页并重新加载
	selectedOrders.value = [];
	currentPage.value = 1;
	hasMore.value = true;
	loadOrders(false);
};

const checkboxChange = (orderId) => {
	const index = selectedOrders.value.indexOf(orderId);
	if (index > -1) {
		selectedOrders.value.splice(index, 1);
	} else {
		selectedOrders.value.push(orderId);
	}
};

const handleOrderCheck = (orderId, checked) => {
	if (checked) {
		if (!selectedOrders.value.includes(orderId)) {
			selectedOrders.value.push(orderId);
		}
	} else {
		const index = selectedOrders.value.indexOf(orderId);
		if (index > -1) {
			selectedOrders.value.splice(index, 1);
		}
	}
};

const handleSelectAllChange = (checked) => {
	if (checked) {
		selectedOrders.value = filteredOrders.value.map(order => order.id);
	} else {
		selectedOrders.value = [];
	}
};

const selectAllChange = (e) => {
  if (e.detail.value.length > 0) {
    selectedOrders.value = filteredOrders.value.map(order => order.id);
  } else {
    selectedOrders.value = [];
  }
};

const nextStep = () => {
  uni.navigateTo({url: '/pages/invoice/issue'});
};

// 列表项点击：充电tab下跳转到 chargingInvoice-detail 页面
const openDetail = (order) => {
  const tabType = tabs.value[currentTab.value].type;
  if (tabType !== 'charging') return;
  const amountParam = ((order && typeof order.amount === 'number') ? order.amount : Number(order?.amount || 0)).toFixed(2);
  uni.navigateTo({url: `/pages/invoice/chargingInvoice-detail?type=charging&amount=${encodeURIComponent(amountParam)}`});
};

const navigateToHistory = () => {
  uni.navigateTo({url: '/pages/invoice/history'});
};

const navigateToTitles = () => {
  uni.navigateTo({url: '/pages/invoice/title-list'});
};

// 日期格式化为中文（与分组排序统一）
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
};

// 将接口数据映射为页面展示结构
const mapTypeToBadge = (t) => {
  switch (Number(t)) {
    case 1: return '充'; // CHARGE
    case 2: return '停'; // PARK
    case 3: return '占'; // OCCUPIED
    case 11: return '共'; // PILE（共享充电桩）
    case 4: return '卡'; // CARD（月卡费）
    default: return '其'; // 其他
  }
};

const mapTypeToFilter = (t) => {
  switch (Number(t)) {
    case 1: return 'charging';
    case 2: return 'parking';
    default: return 'other';
  }
};

const mapInvoiceOrder = (item) => {
  const rawType = item.orderType ?? item.type; // 可能为null
  const typeStr = mapTypeToFilter(rawType);
  return {
    id: item.id,
    date: formatDateTime(item.createTime),
    location: item.parkName ?? item.typeName ??'未知地点',
    plateNumber: item.plateNumber ?? '未知车牌',
    amount: Number(item.actuallyPaid ?? 0),
    type: typeStr,
    rawType: rawType ?? null,
    badge: mapTypeToBadge(rawType)
  };
};

// tab映射为接口orderType
const getOrderTypeByTab = () => {
  const t = tabs.value[currentTab.value].type;
  if (t === 'charging') return 1;
  if (t === 'parking') return 2;
  return 0; // 全部
};

// 加载发票订单（分页）
const loadOrders = async (isLoadMore = false) => {
  if (loading.value) return;
  loading.value = true;
  try {
    const params = {
      orderType: getOrderTypeByTab(),
      pageNo: isLoadMore ? currentPage.value : 1,
      pageSize: pageSize.value
    };
    const data = await InvoiceApi.getInvoiceOrderList(params);
	console.log('getInvoiceOrderList', data);
    const list = Array.isArray(data) ? data : (data?.list || []);
    const mapped = list.map(mapInvoiceOrder);

    if (isLoadMore) {
      orders.value = [...orders.value, ...mapped];
    } else {
      orders.value = mapped;
      currentPage.value = 1;
    }

    hasMore.value = mapped.length === pageSize.value;
    if (hasMore.value) currentPage.value++;
  } catch (e) {
    console.error('获取发票列表失败:', e);
    uni.showToast({ title: '获取发票列表失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// scroll-view 触底加载
const handleScrollToLower = () => {
  if (hasMore.value && !loading.value) {
    loadOrders(true);
  }
};

onMounted(() => {
  loadOrders(false);
});
</script>

<style scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
	position: relative;
}

.fixed-header {
	/* position: fixed; */
	/* top: 0;
	left: 0;
	right: 0;
	z-index: 100; */
	background-color: #fff;
}

.tabs {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 20rpx 0 0 0;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
	font-size: 16px;
  /* font-size: 30rpx; */
  /* color: #666; */
  padding: 0 20rpx 20rpx 20rpx;
  position: relative;
  text-align: center;
  flex: 1;
  max-width: 120rpx;
}

.tab-item.active {
	/* color: #1DCFB7;
	font-weight: bold; */
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  /* width: 80rpx; */
  height: 4rpx;
  background-color: #1DCFB7;
  border-radius: 2rpx;
  width: 100px;
}

.order-list {
	background-color: #fff;
	flex: 1;
	padding: 0;
	/* 预留底部空间，避免与固定footer重叠 */
	padding-bottom: 420rpx;
	/* 移除固定高度，允许内容自适应滚动区域 */
	/* height: calc(100vh - 380rpx); */
}

.loading-tip {
	text-align: center;
	padding: 30rpx 0;
	color: #999;
	font-size: 28rpx;
}

.month-header {
	font-size: 28rpx;
	/* color: #999; */
	margin-left: 20rpx;
	padding: 20rpx 0;
	background-color: #f5f5f5;
}

.order-items-container {
	background-color: #fff;
	/* border-radius: 12rpx; */
	overflow: hidden;
}

.order-item {
	margin: 25rpx 5rpx 25rpx 5rpx;
	display: flex;
	align-items: flex-start;
	padding: 20rpx;
	position: relative;
}

.order-item:not(:last-child)::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20rpx;
  right: 0;
  height: 1rpx;
  background-color: #eee;
}

.checkbox-container {
	display: flex;
	align-items: center;
	margin-right: 10rpx;
}

/* 圆形checkbox样式已在组件内部实现 */

.order-type-badge {
	width: 65rpx;
	height: 65rpx;
	background-color: #fff;
	color: #78787A;
	border-radius: 8rpx;
	font-size: 35rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0 25rpx 0 25rpx;
	border: 1rpx solid #1DCFB7;
}

.order-info {
	flex: 1;
}

.info-line {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8rpx;
}

.info-line:last-child {
	margin-bottom: 0;
}

.location {
	font-size: 30rpx;
	color: #000000;;
}

.plate-number {
	font-size: 28rpx;
	color: #666;
}

.date {
	font-size: 26rpx;
	color: #999;
}

.amount {
	font-size: 30rpx;
	color: #000000;;
}

.footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	flex-direction: column;
	background-color: #fff;
	/* border-top: 1rpx solid #eee; */
	z-index: 1000;
	/* 适配底部安全区，避免遮挡 */
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
}

.footer-top {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
}

.select-all {
	display: flex;
	align-items: center;
}

.checkbox-wrapper {
	display: flex;
	align-items: center;
}

/* 全选圆形checkbox样式已在组件内部实现 */

.select-all-text {
	margin-left: 10rpx;
	font-size: 28rpx;
	color: #000000;;
}

.reminder-text {
	font-size: 24rpx;
	color: #999;
}

.divider {
	height: 1rpx;
	background-color: #eee;
	width: 100%;
}

.action-buttons {
	text-align: center;
	font-size: 30rpx;
	font-weight: normal;
	display: flex;
	justify-content: space-between;
	padding: 20rpx 30rpx;
}

.action-btn {
	background-color: #fff;
	/* color: #1DCFB7; */
	border-radius: 50rpx;
	padding: 0 40rpx;
	/* height: 80rpx; */
	line-height: 80rpx;
	/* font-size: 30rpx; */
	border: 1rpx solid #1DCFB7;
	width: 35%;
}

.footer-bottom {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	margin-bottom: 30rpx;
}

.footer-left {
	display: flex;
	flex-direction: column;
	flex: 1;
}

.btn-container {
	width: 45%;
	display: flex;
	justify-content: flex-end;
}

.summary {
	display: flex;
	align-items: baseline;
	font-size: 28rpx;
	margin-bottom: 10rpx;
}

.total-label {
	font-size: 28rpx;
	color: #000000;;
}

.total-amount {
	font-size: 32rpx;
	color: #000000;;
}

.order-count {
	display: block;
	font-size: 24rpx;
	/* color: #000000; */
	margin-top: 4rpx;
	/* margin-left: auto; */
	/* margin-right: auto; */
}

.next-step-btn {
	text-align: center;
	background-color: #1DCFB7;
	color: #fff;
	border-radius: 50rpx;
	padding: 0 40rpx;
	height: 80rpx;
	line-height: 80rpx;
	/* font-size: 30rpx; */
	border: none;
	width: 100%;
}

.next-step-btn[disabled] {
	background-color: #ccc;
}
</style>
